using System.Collections.Generic;
using UnityEngine;
using UFrame;

public class EffectAgent : AgentContext<EffectAgent>
{
    protected Dictionary<int, int> m_effectTypeDic;
    protected GameObjectPoolContext objectContext;

    protected override void OnCreate()
    {
        base.OnCreate();
        m_effectTypeDic = new Dictionary<int, int>();
        objectContext = GameObjectPoolAgent.Instance.GetPoolContext("[EffectAgent-Pool]");
    }

    public void Play(int effectId, Vector3 pos, bool playAudio, System.Action<GameObject> onCreate = null)
    {
        var effectInfo = TableAgent.Instance.GetEffectCfgById(effectId);
        if (effectInfo == null)
        {
            Debug.LogError("Effect Config NotExists!" + effectId);
            return;
        }

        if (effectInfo.sfx_id > 0 && playAudio)
        {
            SoundAgent.PlayAudioById(effectInfo.sfx_id,pos);
        }

        if (objectContext.ExistPool(effectId))
        {
            var effect = objectContext.GetInstance(effectId);
            PlayEffectAtPos(effect, pos, effectInfo.duration);
            if (onCreate != null)
            {
                onCreate.Invoke(effect);
            }
            return;
        }

        var sourcePath = effectInfo.source;
        var obj = SourceAgent.Instance.LoadGameObjectInstence(sourcePath);
        if (obj != null)
        {
            m_effectTypeDic[obj.GetInstanceID()] = effectId;
            PlayEffectAtPos(obj, pos, effectInfo.duration);
            if (onCreate != null)
            {
                onCreate.Invoke(obj);
            }
        }
    }

    protected void PlayEffectAtPos(GameObject effect, Vector3 pos, float duration)
    {
        effect.transform.SetParent(objectContext.Root);
        effect.transform.position = pos;
        effect.gameObject.SetActive(true);
        var effectBehaviour = effect.GetComponent<EffectBehaviour>();
        if (!effectBehaviour)
            effectBehaviour = effect.AddComponent<EffectBehaviour>();
        effectBehaviour.Play(duration * 0.001f);
    }

    public void SaveBackEffect(GameObject effect)
    {
        if (!effect)
            return;
        if (m_effectTypeDic.TryGetValue(effect.GetInstanceID(), out int effectId))
        {
            objectContext.SaveBack(effectId, effect);
        }
        else
        {
            GameObject.Destroy(effect);
        }
    }
}
